<?php

namespace application\admin\controller;

use ticky\request;
use ticky\config;

class setting extends base {

    public function index() {
        global $_G;
        if (request::isPost()) {
            $this->settingsubmit($setting);
            showmsg('配置成功', '/admin/setting');
        } else {
            $setting = get_config();
            $theme_list = get_theme_all();
            $this->assign('theme_list', $theme_list);
            $this->assign('setting', $setting);
            $this->display('setting/index');
        }
    }

    public function seo() {
        $setting = get_config();
        if (request::isPost()) {
            $this->settingsubmit($setting);
            showmsg('配置成功', '/admin/setting');
        } else {
            $this->assign('setting', $setting);
            $this->display('setting/seo');
        }
    }

    /**
     * 测试邮件配置
     */
    public function public_test_mail() {
        if (sendmail($_GET['mail_to'], 'TickyCMS邮件测试', '这是一封测试邮件，如果您成功接收此邮件，说明您的邮件配置正确！')) {
            exit('发送邮件成功！');
        } else {
            exit('发送邮件失败！');
        }
    }

    private function settingsubmit($setting) {
        $settingnew = request::post('settingnew', []);
        $settings = array();
        foreach ($settingnew as $key => $val) {
            if ($setting[$key] != $val) {
                $settings[$key] = $val;
            }
        }
        if ($settings) {
            $this->update_batch($settings);
        }
        $site_theme = $settingnew['site_theme'];
        config::set('view', ['default_theme' => $site_theme]);
    }

    private function update_batch($array) {
        $settings = array();
        foreach ($array as $key => $value) {
            $key = addslashes($key);
            $value = addslashes(is_array($value) ? serialize($value) : $value);
            $settings[] = "('$key', '$value')";
            db('setting')->delete(['skey' => $key]);
            cache('setting', null);
        }
        if ($settings) {
            cache('setting', null);
            $prefix = config::get('db')['prefix'];
            return db('setting')->query("REPLACE INTO " . $prefix . 'setting' . " (`skey`, `svalue`) VALUES " . implode(',', $settings));
        }
        return false;
    }

}
